package com.mingmen.canting.chushizhang;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.activity.YuCaiGouDanActivity;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.OnItemClickListener;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.dialog.ButtomDialogView;
import com.mingmen.canting.flycotablelayout.flyco.tablayout.widget.MsgView;
import com.mingmen.canting.fragment.BaseFragment;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.ChushiShenHeModel;
import com.mingmen.canting.model.PurCountModel;
import com.mingmen.canting.model.ShenHeModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class ChuShiOrderFragment extends BaseFragment implements ChuShiDingShenAdapter.OnItemClickListener {
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    Unbinder unbinder;
    private String mTitle;

    @BindView(R.id.recycler_view)
    SwipeRecyclerView recycler_view;
    String token;
    private ChuShiDingShenAdapter mAdapter;
    List<ChushiShenHeModel.DataBean> dataBeanList = new ArrayList<>();
    List<String> stringList = new ArrayList<>();
    String startTime = "";
    String endTime = "";
    int flag = 0;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;

    @BindView(R.id.btn_suofang)
    Button btnSuofang;
    @BindView(R.id.image_yucaigou)
    ImageView image_yucaigou;

    @BindView(R.id.img_yucaigou)
    ImageView imgYucaigou;
    String yuCaigouData;
    @BindView(R.id.rtv_msg_tip2)
    MsgView rtv_msg_tip2;
    private int resurtResurant = 100;
    @BindView(R.id.rtv_msg_tip)
    MsgView rtv_msg_tip;
    @BindView(R.id.btn_digndan)
    Button btn_digndan;
    @BindView(R.id.img_list)
    ImageView imgList;
    @BindView(R.id.btn_AuditReject)
    Button btn_AuditReject;
    ButtomDialogView bottomSheetDialog;
    @BindView(R.id.btn_AuditPass)
    Button btn_AuditPass;
    @BindView(R.id.btn_suofangyi)
    Button btn_suofangyi;
    String data;

    public static ChuShiOrderFragment getInstance(String title) {
        ChuShiOrderFragment sf = new ChuShiOrderFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_chushi_order, null);
        unbinder = ButterKnife.bind(this, v);
        EventBus.getDefault().register(this);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        recycler_view.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                // 根据原position判断该item是否是parent item
                if (mAdapter.isParentItem(position)) {
                    // 换取parent position
                    final int parentPosition = mAdapter.parentItemPosition(position);
                    // 判断parent是否打开了二级菜单
                    if (dataBeanList.size() == 0) {
                    } else {
                        if (mAdapter.isExpanded(parentPosition)) {
                            dataBeanList.get(parentPosition).setExpended(false);
                            mAdapter.notifyParentChanged(parentPosition);
                            // 关闭该parent下的二级菜单
                            mAdapter.collapseParent(parentPosition);

                        } else {

                            dataBeanList.get(parentPosition).setExpended(true);
                            mAdapter.notifyParentChanged(parentPosition);
                            // 打开该parent下的二级菜单
                            mAdapter.expandParent(parentPosition);

                        }
                    }

                } else {
                    int parentPosition = mAdapter.parentItemPosition(position);
                    // 换取child position
                    int childPosition = mAdapter.childItemPosition(position);
                    String message = String.format("我是%1$d爸爸的%2$d儿子", parentPosition, childPosition);
                    dataBeanList.get(parentPosition).setExpended(false);
                }

            }
        });
        mAdapter = new ChuShiDingShenAdapter(getActivity(), dataBeanList, flag);
        recycler_view.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(this);
//        HttpResponse.getApplyListByOrder(token, "0", startTime, endTime, flag + "", new StringCallback(getActivity()) {
        getListData(token, "0", "", "", flag + "");
        HttpResponse.getPrePurchaseCount(token, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getPrePurchaseCount", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    PurCountModel purchaseCountModel = GsonUtil.GsonToBean(s, PurCountModel.class);
                    rtv_msg_tip.setText(purchaseCountModel.getData().get(0).getCount() + "");
                    rtv_msg_tip2.setText(purchaseCountModel.getData().get(0).getCount() + "");
                }

            }
        });
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;
        return v;
    }


    @Override
    public void initData() {

    }

    public void getListData(String token, String st, String startTime, String endTime, String flag) {
//        HttpResponse.getApplyListByOrder(token, "0", startTime, endTime, flag + "", new StringCallback(getActivity()) {
        HttpResponse.getApplyListByOrder(token, st, startTime, endTime, flag + "", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }
                if (stringList.size() > 0) {
                    stringList.clear();
                }
                Log.d("dingdan", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    ChushiShenHeModel chushiShenHeModel = new ChushiShenHeModel();
                    chushiShenHeModel = GsonUtil.GsonToBean(s, ChushiShenHeModel.class);
                    dataBeanList.addAll(chushiShenHeModel.getData());
                    Log.d("Daddkdkdk", dataBeanList.size() + "");
                    if (dataBeanList.size() == 0) {
                        layout_nodata.setVisibility(View.VISIBLE);
                    } else {
                        layout_nodata.setVisibility(View.GONE);
                    }
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        stringList.add(dataBeanList.get(i).getApplyId());
                    }
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        dataBeanList.get(i).setExpended(false);
                    }
                    mAdapter.setGroupList(dataBeanList);
                    mAdapter.notifyDataSetChanged();
                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                layout_nodata.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.card_title_tv, R.id.btn_suofang, R.id.img_yucaigou, R.id.btn_digndan, R.id.img_list, R.id.btn_AuditReject, R.id.btn_AuditPass, R.id.image_yucaigou, R.id.btn_suofangyi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_suofang:
                btn_digndan.setVisibility(View.GONE);
                btnSuofang.setVisibility(View.VISIBLE);
                imgList.setVisibility(View.VISIBLE);
                break;
            case R.id.img_yucaigou:

                Intent intent = new Intent(getActivity(), YuCaiGouDanActivity.class);

                intent.putExtra("yuCaigouData", yuCaigouData);
                startActivityForResult(intent, resurtResurant);
                break;
            case R.id.btn_digndan:
                startActivity(new Intent(getActivity(), ChuShiZhangNewDingDanActivity.class));
                break;
            case R.id.img_list:
                imgList.setVisibility(View.GONE);
                btn_digndan.setVisibility(View.VISIBLE);
                btnSuofang.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_AuditReject:
                if (stringList.size() == 0) {
                    Toast.makeText(mContext, "当前无订单", Toast.LENGTH_SHORT).show();
                } else {
                    List<String> bohui = new ArrayList<>();
                    JSONObject jsonObject = new JSONObject();
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        for (int j = 0; j < dataBeanList.get(i).getDetails().size(); j++) {
                            try {
                                jsonObject.put("applyDetailId", dataBeanList.get(i).getDetails().get(0).getDetailId());
                                jsonObject.put("rejectReason",dataBeanList.get(i).getDetails().get(0).getMark());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            bohui.add(jsonObject.toString());
                        }

                    }

                    Log.d("bohuibohuibohuibohui", bohui.toString());
//                [{"applyDetailId":"1290540760504078336","rejectReason":"菜品不好"}]
                    HttpResponse.setAuditReject(token, bohui.toString(), new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("setAuditRejectsetAuditReject", s);
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
//                                bottomSheetDialog.dismiss();
//                                            getListData();
                                getListData(token, "0", "", "", flag + "");
                            }
                            Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();

                        }
                    });
                }


                break;
            case R.id.btn_AuditPass:
                if (stringList.size() == 0) {
                    Toast.makeText(mContext, "当前无订单", Toast.LENGTH_SHORT).show();
                } else {

                    String string1 = MyStringUtils.returnStringBuffer(stringList);

                    Log.d("AUDITPASS", string1);
                    HttpResponse.setAuditPass(token, string1, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            ShenHeModel shenHeModel = new ShenHeModel();
                            shenHeModel = GsonUtil.GsonToBean(s, ShenHeModel.class);
                            if (shenHeModel.getCode() == 0) {
                                getListData(token, "0", "", "", flag + "");
//                                getListData();
                            }
                            Toast.makeText(mContext, shenHeModel.getMessage() + "", Toast.LENGTH_SHORT).show();

                        }
                    });
                }


                break;
            case R.id.image_yucaigou:
                imgYucaigou.setVisibility(View.VISIBLE);
                image_yucaigou.setVisibility(View.GONE);
                rtv_msg_tip.setVisibility(View.VISIBLE);
                rtv_msg_tip2.setVisibility(View.GONE);
                break;
            case R.id.btn_suofangyi:
                imgYucaigou.setVisibility(View.GONE);
                image_yucaigou.setVisibility(View.VISIBLE);
                rtv_msg_tip.setVisibility(View.GONE);
                rtv_msg_tip2.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onItemClickListener(View view, int parentPosition, int position, List<ChushiShenHeModel.DataBean> groupList, List<ChushiShenHeModel.DataBean.DetailsBean> memberList) {
        switch (view.getId()) {
            case R.id.text_cancel:
                HttpResponse.setAuditCancel(token, "2", groupList.get(parentPosition).getDetails().get(position).getDetailId(), new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("DKkdkdkdkdkdk", s);
                        BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                        if (baseBean.getCode() == 0) {
//                            getListData();
                            getListData(token, "0", "", "", flag + "");
//                                    dataBeanList.get(parentPosition).getDetails().remove(position);
//                            mAdapter.notifyDataSetChanged();
                        }
                        Toast.makeText(getActivity(), baseBean.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                });
                break;
            case R.id.layout_id:
                createDialog(parentPosition, position, groupList, memberList);
                break;
        }
    }


    public void createDialog(int parentPosition, int position, List<ChushiShenHeModel.DataBean> groupList, List<ChushiShenHeModel.DataBean.DetailsBean> memberList) {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

        View view1 = layoutInflater.inflate(R.layout.dialog_chushi_bottom, null);

        bottomSheetDialog = new ButtomDialogView(getActivity(), view1, true, true);
        bottomSheetDialog.setContentView(R.layout.toast_dialog);
        bottomSheetDialog.show();
        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 4);
        recycle_biaoqian.setLayoutManager(gridLayoutManager);

        ImageView img_close = view1.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });

        EditText verify_et = view1.findViewById(R.id.verify_et);

        TextView text_submit = view1.findViewById(R.id.text_submit);
        text_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.d("text_submittext_submit", token);
                Log.d("text_submittext_submit", groupList.get(parentPosition).getDetails().get(position).getDetailId());
                List<String> bohui = new ArrayList<>();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("applyDetailId", groupList.get(parentPosition).getDetails().get(position).getDetailId());
                    jsonObject.put("rejectReason", "菜品不好");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                bohui.add(jsonObject.toString());
                Log.d("bohuibohui", bohui.toString());
//                [{"applyDetailId":"1290540760504078336","rejectReason":"菜品不好"}]
                groupList.get(parentPosition).getDetails().get(parentPosition).setMark("菜品不好");
                mAdapter.notifyDataSetChanged();
                btn_AuditPass.setEnabled(false);
                btn_AuditPass.setBackground(getResources().getDrawable(R.drawable.chushi_gray));
                bottomSheetDialog.dismiss();
                /*   HttpResponse.setAuditReject(token, bohui.toString(), new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("setAuditRejectsetAuditReject", s);
                        BaseBean baseBean = new BaseBean();
                        baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                        if (baseBean.getCode() == 0) {
                            bottomSheetDialog.dismiss();
                            EventBus.getDefault().post(30);
//                            getListData();
                            getListData(token, "0", "", "", flag + "");
                        }
                        Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    }
                });*/

            }
        });

    }

    public void onEventMainThread(Integer integer) {
        if (integer == 31) {
//    getListData();
            getListData(token, "0", "", "", flag + "");
        }

    }
}